package com.xinsoft.controller.sale;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xinsoft.common.ApprovedParam;
import com.xinsoft.common.Response;
import com.xinsoft.constant.Const;
import com.xinsoft.entity.dto.*;
import com.xinsoft.entity.po.*;
import com.xinsoft.entity.vo.ScmSaleListVo;
import com.xinsoft.entity.vo.ScmSalePriceVo;
import com.xinsoft.entity.vo.ScmSaleVo;
import com.xinsoft.service.*;
import com.xinsoft.utils.ExcelUtils;
import com.xinsoft.utils.TokenUtil;
import com.xinsoft.validator.ValidatorUtils;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 云供应链/销售管理/销售订单
 */
@Slf4j
@RestController
@RequestMapping("/scm/sale")
public class ScmSaleController {
    @Autowired
    private ScmSaleService saleService;
    @Autowired
    private ScmSaleItemService saleItemService;
    @Autowired
    private SysClientService clientService;
    @Autowired
    private SysClientLevelService clientLevelService;
    @Autowired
    private ScmSalePriceService salePriceService;
    @Autowired
    private ApproveService approveService;

    /**
     * 分页
     */
    @PostMapping("/pageList")
    public Response<IPage<ScmSaleListVo>> pageList(@RequestBody ScmSalePageParam scmSalePageParam) {
        log.info("销售订单分页查询参数：{}", JSON.toJSONString(scmSalePageParam));
        scmSalePageParam.setCurrentUserId(TokenUtil.getUserId());
        return Response.succeed(saleService.findPageListByParam(scmSalePageParam));
    }

    /**
     * 暂存
     */
    @PostMapping("/addOrUpdate")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> addOrUpdate(@RequestBody ScmSaleDTO scmSaleDTO) {
        log.info("销售订单-暂存数据：{}", JSON.toJSONString(scmSaleDTO));
        // 参数校验
        ValidatorUtils.validateEntity(scmSaleDTO);
        saleService.tempSave(scmSaleDTO);
        return Response.succeed();
    }

    /**
     * 提交审批
     */
    @PostMapping("/submitApprove")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> submitApprove(@RequestBody ScmSaleDTO scmSaleDTO) {
        log.info("销售订单-提交数据：{}", JSON.toJSONString(scmSaleDTO));
        Integer id = saleService.tempSave(scmSaleDTO);
        ApproveDTO approveDTO = new ApproveDTO();
        approveDTO.setSourceId(id);
        approveDTO.setSourceType(Const.ApproveType.XSDD);
        approveDTO.setSourceTypeName(Const.ApproveTypeName.XSDD);
        return approveService.submitApprove(approveDTO);
    }

    /**
     * 审批
     */
    @PostMapping("/approved")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> approved(@Validated @RequestBody ApprovedParam param) {
        log.info("销售订单-审批参数：{}", JSON.toJSONString(param));
        Response<?> approved = approveService.approved(param, Const.ApproveType.XSDD);
        ScmSale sale = saleService.getById(param.getId());
        // 审批成功，将销售价格写入物料销售价格明细
        if (approved.isSuccess() && Const.ApproveStatus.APPROVED.equals(sale.getApproveStatus())) {
            SysClient client = clientService.getById(sale.getClientId());
            SysClientLevel clientLevel = clientLevelService.getById(client.getLevelId());
            List<ScmSaleItem> itemList = saleItemService.list(Wrappers.lambdaQuery(ScmSaleItem.class).eq(ScmSaleItem::getSaleId, param.getId()));
            List<ScmSalePrice> priceList = new ArrayList<>();
            itemList.forEach(item->{
                ScmSalePrice price = new ScmSalePrice();
                price.setMaterialId(item.getMaterialId());
                // price.setMaterialName();
                price.setTaxUnitPrice(item.getTaxUnitPrice());
                price.setSaleNum(item.getSaleNum());
                price.setSaleTime(sale.getUpdateTime());
                price.setClientId(sale.getClientId());
                price.setClientName(client.getClientName());
                price.setLevelName(clientLevel.getLevelName());
                priceList.add(price);
            });
            salePriceService.saveBatch(priceList);
        }
        return approved;
    }

    /**
     * 审批流程
     */
    @GetMapping("/approveHis")
    public Response<?> approveHis(@RequestParam(value = "id") Integer id){
        return Response.succeed(approveService.approvalHistory(id, Const.ApproveType.XSDD));
    }

    /**
     * 获取详情
     *
     * @param id 销售订单id
     * @return {@link Response}<{@link ?}>
     */
    @GetMapping("/detail")
    public Response<ScmSaleVo> detail(@RequestParam(value = "id", defaultValue = "") Integer id) {
        ScmSaleVo vo = saleService.detail(id);
        // 审批记录
        vo.setScmApproveHisList(approveService.approvalHistory(id, Const.ApproveType.XSDD));
        return Response.succeed(vo);
    }

    /**
     * 删除
     */
    @PostMapping("/del")
    @Transactional(rollbackFor = Exception.class)
    public Response<?> del(@RequestBody List<Integer> ids) {
        List<Integer> newIds = ids.stream().distinct().collect(Collectors.toList());
        saleService.del(newIds);
        return Response.succeed();
    }

    /**
     * 关闭
     * @param ids 销售订单ids
     * @return {@link Response}<{@link ?}>
     */
    @PostMapping("/close")
    public Response<?> close(@RequestBody List<Integer> ids) {
        saleService.close(ids);
        return Response.succeed();
    }

    /**
     * 开启（反关闭）
     * @param ids 销售订单ids
     * @return {@link Response}<{@link ?}>
     */
    @PostMapping("/reverseClose")
    public Response<?> reverseClose(@RequestBody List<Integer> ids) {
        saleService.reverseClose(ids);
        return Response.succeed();
    }

    /**
     * 行关闭
     * @param scmSaleItemDTO
     * @return {@link Response}<{@link ?}>
     */
    @PostMapping("/lineClose")
    public Response<?> lineClose(@RequestBody ScmSaleItemDTO scmSaleItemDTO) {
        ValidatorUtils.validateEntity(scmSaleItemDTO);
        saleService.lineClose(scmSaleItemDTO);
        return Response.succeed();
    }

    /**
     * 历史售价
     * @return {@link Response}<{@link ?}>
     */
    @GetMapping("/historyPrice")
    public Response<ScmSalePriceVo> historyPrice(@RequestParam("clientId") Integer clientId, @RequestParam("materialId") Integer materialId) {
        return Response.succeed(saleService.historyPrice(clientId, materialId));
    }

    /**
     * 导出
     */
    @PostMapping("/export")
    public Response<?> export(@RequestBody @ApiParam("查询参数") ScmSalePageParam salePageParam, HttpServletResponse response) throws Exception {
        List<ScmSaleListVo> scmSaleListList = saleService.findListByParam(salePageParam);
        ExcelUtils.exportByEasypoi(scmSaleListList, ScmSaleListVo.class, "销售订单", "销售订单", response, "销售订单");
        return Response.succeed();
    }

}
